const {
  http
} = require("../../../utils/apiutils")
const
  util = require("../../../utils/util")
const {input}  =require('../../../utils/tools');
const app = getApp()
Page({

  data: {
    tabActive: 2,   // 全职2  兼职1
    sh: 0,
    item:'',
    limitTop: 0,
    limitBottom: 0,
    shs: 0,
    statusBar: 0,
    CustomBar: 0,
    canvasShow: false,
    limit: 10,
    itemHeight: 0,
    dataList: [],
    pageNo: 1,
    total: 1,
    latitude: 0,
    longitude: 0,
    action: 0,
    actionCur: {},
    type:2,
    showPlaying:true,
    jiaonang:{}, // 胶囊数据
  },
  input(e){
    input.bind(this)(e);
    wx.nextTick(res=>{
      console.log(this.data.item)
    })
  },
  tabChange(event){
    let title = event.detail.title;
    let name = event.detail.name;
    this.setData({
      pageNo:1,
      total:1,
      dataList:[],
      type:event.detail.name,
      tabActive:event.detail.name
    })
    wx.nextTick(()=>{
      this.getJob()
    })
  },
  onShareAppMessage: function () {
    var shareObj = {
      title: "分享岗位", // 默认是小程序的名称(可以写slogan等)
      path: getApp().globalData.userInfo.inviteCode?'/pages/index/index?code='+getApp().globalData.userInfo.inviteCode:'/pages/index/index', // 
      imageUrl: '',
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
        }
      }
    }
    console.log("------------", shareObj);
    // 返回shareObj
    return shareObj;
  },
  onclickSearch: function () {
    wx.navigateTo({
      url: '/pages/home/pages/search/search',
    })
  },
  //检测活动距离
  scroll: function (e) {
    if (e.detail > this.data.CustomBar) {
      this.setData({
        ts: true,
      })
    } else {
      this.setData({
        ts: false,
      })
    }


    console.log("---------滑动距离---", e);
  },

  onclickInfo: function () {
    console.log('isLogin',getApp().globalData.isLogin)
    if (!app.globalData.isLogin) {
      wx.showModal({
        title: "提示",
        content: "您还没有登录，登陆后即可查看详情",
        confirmText: "去登陆",
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login?ptype=home',
            })
          }
        }
      })
      return;
    }

    if (this.data.action == 1) {
      if (this.data.actionCur.status == 4) {
        let data = {
          id: this.data.actionCur.id,
          name: this.data.actionCur.jobName,
          workplace: this.data.actionCur.workplace,
          type: 2,
          jobId: this.data.actionCur.jobId,
        }
        wx.navigateTo({
          url: '/pages/clockin/clockin?data=' + encodeURIComponent(JSON.stringify(data)),
        })

      } else if (this.data.actionCur.status == 3) {
        // console.log("-------到岗打卡-----",item);
        // this.clockIn(item.id);
        var interviewDate = "";
        var str = this.data.actionCur.interviewDate;
        if (str) {
          str = str.substring(0, 19);
          str = str.replace(/-/g, '/');
          let date = new Date(str);
          interviewDate = date.getFullYear().toString() + "-" + (date.getMonth() + 1).toString() + "-" + date.getDate().toString(); // 年
        }
        let data = {
          id: this.data.actionCur.id,
          name: this.data.actionCur.jobName,
          workplace: this.data.actionCur.workplace,
          type: 1,
          jobId: this.data.actionCur.jobId,
          interviewDate: interviewDate,
        }
        wx.navigateTo({
          url: '/pages/clockin/clockin?data=' + encodeURIComponent(JSON.stringify(data)),
        })


      } else {
        wx.navigateTo({
          url: '/pages/me/pages/action2/action?type=3',
        })
      }


    } else {
      wx.navigateTo({
        url: '/pages/me/pages/action2/action?type=3',
      })
    }

    // if (this.data.action == 1) {
    //   let item = this.data.actionCur;
    //   console.log("--------", item);
    //   let data = {
    //     id: item.id,
    //     name: item.jobName,
    //     workplace: item.workplace,
    //     type: 2,
    //     jobId: item.jobId
    //   }

    //   wx.navigateTo({
    //     url: '/pages/clockin/clockin?data=' + encodeURIComponent(JSON.stringify(data)),
    //   })
    // } else {
    //   wx.navigateTo({
    //     url: '/pages/me/pages/duty/duty',
    //   })
    // }


  },
  onclickCell: function (e) {
    console.log('isLogin',getApp().globalData.isLogin)
    if (!app.globalData.isLogin) {
      wx.showModal({
        title: "提示",
        content: "您还没有登录，登陆后即可查看详情",
        confirmText: "去登陆",
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login?ptype=home',
            })
          }
        }
      })
      return;
    }
    let item = e.currentTarget.dataset.item;
    // if (index % 2 == 0) {
    //   wx.navigateTo({
    //     url: '/pages/home/pages/train/train',
    //   })
    // } else {
    wx.navigateTo({
      url: '/pages/home/pages/work/work?id=' + item.id,
    })
    // }
  },

  onclickswiper:function(e){

    let item = e.currentTarget.dataset.item;
    if(item.video)
    {
      wx.setStorageSync('video', JSON.stringify(item))
      wx.navigateTo({
        url: '/pages/home/pages/video/video',
      })
    }else if(item.jobImage){
      wx.navigateTo({
        url: '../../home/pages/sq/sq?img='+item.jobImage+'&id='+item.eventId,
      })
    }
    else
    {
      wx.showToast({
        title: '暂无详细介绍',
        icon:"none",
      })
    }

  },
  getJob() {
    var data = {
      "pageNo": this.data.pageNo, //手机号码
      "pageSize": "50", //密码
      type:this.data.type
    }
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    http.getJob(data,
      function (res) {
        wx.hideLoading()
        console.log("------用户登录信息哦---", res);
        if (res.code == 0) {
          var pageNo = res.data.current;
          var total = res.data.pages;
          var arr = res.data.records;
          arr.forEach(element => {
            if (!that.data.latitude == 0) {
              let ds = util.getDistance(that.data.latitude, that.data.longitude, element.lat, element.lng);
              console.log("-----------", ds)
              if(element.stationFollow==1)
              {
                element.dst = 0
              }
              else
              {
                element.dst = ds;
              }
              if (ds > 1) {
                element.ds = ds.toFixed(1) + "公里"
              } else {
                element.ds = (ds * 1000).toFixed(0) + "米"
              }
            } else {
              element.ds = "未知"
              element.dst = 0;
            }
          });
          arr = arr.sort(compare("dst"))
          if (pageNo == 1) {
            that.setData({
              dataList: arr,
              pageNo,
              total
            })
          } else if (pageNo <= total) {
            that.setData({
              dataList: [...that.data.dataList, ...arr],
              pageNo,
              total
            })
          }
        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })
  },
  onLoad: function (options) {
    console.log(999)
    console.log(wx)
    // this.getcarousel();
    // this.getcapsule();
    // this.isGetSetting();
  },
  getcarousel: function () {
    var that = this;
    http.getcarousel({},
      function (res) {
        console.log("---轮播图-",res);
        if (res.code == 0) {
          var arr = res.data;
          that.setData({
            imgList:arr,
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })


  },
  onReady: function () {

  },
  change: function (e) {
    this.setData({
      active: e.detail.index
    })
  },

  getclockInInfo: function () {
    var data = {
      "pageNo": 1,
      "pageSize": "10",
      "statusList": "3,4",
    }
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    http.getregistration(data,
      function (res) {
        wx.hideLoading()
        console.log("------报名岗位列表---", res);
        if (res.code == 0) {
        var arr = res.data.records;
        // if (arr.length == 1) {
        //   that.setData({
        //     actionCur: arr[0],
        //     action: 1
        //   })
        // } else 
        if (arr.length > 0) {
            that.setData({
              actionCur: arr[0],
              action: 2,
              showPlaying:true
            })
            console.log(that.data.actionCur);
          }else{
            that.setData({
              showPlaying:false
            })
          }
        }
      },
      function (err) {
        wx.hideLoading()
      })

  },
  bindscrolltolower:function(){
    if(this.data.pageNo == this.data.total)
    {
      wx.showToast({
        title: '没有更多岗位了',
        icon:"none",
      })
    }
    else
    {
        this.data.pageNo = this.data.pageNo+1;
        this.getJob()
    }
  },
  isGetSetting() {
    // 判断用户是否授权
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        that.data.latitude = res.latitude;
        that.data.longitude = res.longitude;
        console.log("-----用户位置信息--", res)
      },
      fail: function (res) {
        console.log(2222,res)
        wx.showModal({
          title:'获取当前定位',
          content:'请打开设置，允许小程序使用位置信息',
          cancelText: '不允许',
          confirmText:'打开设置',
          success(res){
            if(res.confirm){
              wx.openSetting({
                withSubscriptions: true,
                success(res){
                   if(res.authSetting['scope.userLocation']){
                     that.isGetSetting()
                   }
                }
              })
            }
          },
          fail(err){
            console.log(err)
          }
        })
      },
      complete(){
        that.getJob();
      }
    })
    return
    wx.getSetting({
      success: (res) => {
        var statu = res.authSetting;
        if (!statu['scope.userLocation']) { //没授权

          return
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            confirmColor: '#f16765',
            success: res => {
              if (res.confirm) {
                wx.openSetting({
                  success: data => {
                    if (data.authSetting["scope.userLocation"]) {
                      // 调用百度地图，获取位置信息(就是经纬度转换成地址)
                      wx.getLocation({
                        type: 'gcj02',
                        success: function (res) {
                          console.log(res);
                          that.data.latitude = res.latitude;
                          that.data.longitude = res.longitude;
                          that.getJob();
                        },
                      })
                    }
                  }
                })
              } else {
                that.getJob();
              }
            }
          })
        } else { //已授权
          //做一些事情...

          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              that.data.latitude = res.latitude;
              that.data.longitude = res.longitude;
              console.log("-----用户位置信息--", res)
              that.getJob();
            },
            fail: function (res) {
              wx.showToast({
                title: '您没有开启定位服务无法计算距离',
                icon: "none"
              })
              that.getJob();
            }
          })
        }
      }
    })
  },

  onShow: function () {
    var that = this;
    let CustomBar = app.globalData.CustomBar;
    let statusBar = app.globalData.statusBar
    this.setData({
      CustomBar: CustomBar - statusBar,
      statusBar: statusBar,
    })
    wx.getSystemInfo({
      success: (result) => {
        console.log(11111,result)
        var spx = 415 / 750 * result.windowWidth;
        that.setData({
          sh: result.windowHeight - CustomBar,
          shs: result.windowHeight - CustomBar - spx ,
        })
      },
    })
    if (app.globalData.isLogin) {
      this.getclockInInfo();
    }
    this.getcarousel();
    this.getcapsule();
    this.isGetSetting();
  },
  onPageScroll() {

  },
  onPullDownRefresh: function () {
    this.onShow();
  },
  hasLogin(e){
    console.log('isLogin',getApp().globalData.isLogin)
    let url = e.currentTarget.dataset.url;
    if (!app.globalData.isLogin) {
      wx.showModal({
        title: "提示",
        content: "您还没有登录，登陆后即可查看详情",
        confirmText: "去登陆",
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login',
            })
          }
        }
      })
      return;
    }
    wx.navigateTo({
      url
    })
  },
  getcapsule(){
    http.capsule({},res=>{
      if(res.code==0){
        this.setData({
          jiaonang:res.data
        })
      }else{
        wx.showToast({
          title: res.message,
        })
      }
    },err=>{})
  },
  showCode(){
    // wx.previewImage({
    //   urls: ['http://linghuoimage.xbbzp.com/Fpeh_EX4rVCCAZ8ZL-MAf5HfUiAF'],
    //   // urls: ['http://linghuoimage.xbbzp.com/Fo7Wv7FFziwAvH8fFDeFSw_CetA3'],
    // })
    wx.navigateTo({
      url: '/pages/tabBar/home/webview',
    })
  }
})

function compare(property) {
  return function (a, b) {
    var value1 = a[property];
    var value2 = b[property];
    return value1 - value2;
  }
}